<template>
  <div class="user-photos">
    <div class="page-header">
      <h2>我的作品</h2>
      <el-button type="primary" icon="el-icon-plus" @click="uploadDialogVisible = true">上传作品</el-button>
    </div>
    
    <div class="empty-block" v-if="photoList.length === 0">
      <el-empty description="暂无作品，快来上传你的摄影作品吧！">
        <el-button type="primary" @click="uploadDialogVisible = true">上传作品</el-button>
      </el-empty>
    </div>
    
    <div v-else class="photo-grid">
      <transition-group name="photo-list" tag="div" class="grid-container">
        <div v-for="photo in photoList" :key="photo.id" class="photo-item">
          <el-card shadow="hover" class="photo-card">
            <div class="photo-preview" @click="viewPhotoDetail(photo.id)">
              <el-image 
                :src="photo.imgUrl" 
                fit="cover"
                :preview-src-list="[photo.imgUrl]">
                <div slot="error" class="image-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <div class="photo-overlay">
                <span class="view-text">查看详情</span>
              </div>
            </div>
            
            <div class="photo-content">
              <h3 class="photo-title">{{ photo.title }}</h3>
              
              <div class="photo-meta">
                <el-tag size="small" :type="photo.type === 1 ? 'success' : 'info'" class="photo-tag">
                  {{ photo.type === 1 ? '手机摄影' : '相机摄影' }}
                </el-tag>
                <el-tag size="small" :type="getStatusTagType(photo.status)" class="photo-tag">
                  {{ getStatusText(photo.status) }}
                </el-tag>
              </div>
              
              <div class="photo-stats">
                <div class="stat-item">
                  <i class="el-icon-star-on"></i>
                  <span>{{ photo.score.toFixed(1) }}</span>
                </div>
                <div class="stat-item">
                  <i class="el-icon-tickets"></i>
                  <span>{{ photo.voteCount }}</span>
                </div>
                <div class="stat-item">
                  <i class="el-icon-view"></i>
                  <span>{{ photo.viewCount }}</span>
                </div>
              </div>
              
              <div class="photo-actions">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click.stop="handleEdit(photo)">
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click.stop="handleDelete(photo)">
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </transition-group>
      
      <div class="pagination" v-if="total > 0">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    
    <!-- 上传作品对话框 -->
    <el-dialog
      title="上传作品"
      :visible.sync="uploadDialogVisible"
      width="500px">
      <el-form :model="photoForm" :rules="photoRules" ref="photoForm" label-width="80px">
        <el-form-item label="作品图片" prop="file">
          <el-upload
            class="photo-uploader"
            action="/api/photos/upload"
            :http-request="customUpload"
            :show-file-list="false"
            :on-success="handlePhotoSuccess"
            :before-upload="beforePhotoUpload">
            <img v-if="photoForm.imgUrl" :src="photoForm.imgUrl" class="photo">
            <i v-else class="el-icon-plus photo-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">建议上传高质量的图片，jpg/png格式，大小不超过5MB</div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="photoForm.title" placeholder="请输入作品标题"></el-input>
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="photoForm.type">
            <el-radio :label="1">手机摄影</el-radio>
            <el-radio :label="2">相机摄影</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入作品描述"
            v-model="photoForm.description">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 编辑作品对话框 -->
    <el-dialog
      title="编辑作品"
      :visible.sync="editDialogVisible"
      width="500px">
      <el-form :model="editForm" :rules="photoRules" ref="editForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入作品标题"></el-input>
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="editForm.type">
            <el-radio :label="1">手机摄影</el-radio>
            <el-radio :label="2">相机摄影</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入作品描述"
            v-model="editForm.description">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="editing">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserPhotos',
  data() {
    return {
      photoList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      uploadDialogVisible: false,
      editDialogVisible: false,
      photoForm: {
        title: '',
        type: 1,
        description: '',
        imgUrl: '',
        userId: '',
        author: ''
      },
      editForm: {
        id: '',
        title: '',
        type: 1,
        description: ''
      },
      photoRules: {
        title: [
          { required: true, message: '请输入作品标题', trigger: 'blur' },
          { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择作品类型', trigger: 'change' }
        ],
        description: [
          { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
        ]
      },
      uploading: false,
      editing: false
    }
  },
  computed: {
    ...mapGetters(['userId', 'nickname'])
  },
  created() {
    this.fetchUserPhotos()
  },
  methods: {
    async fetchUserPhotos() {
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          userId: this.userId
        }
        const res = await this.$http.get('/photos/page', { params })
        if (res.data.code === 1) {
          this.photoList = res.data.data.records.map(item => {
            // 使用完整URL以确保图片能够正确显示
            if (item.imgUrl && item.imgUrl.startsWith('/upload/')) {
              // 从window.location.origin获取当前域名，确保图片URL与当前页面同源
              item.imgUrl = `${window.location.origin}/api${item.imgUrl}`;
              console.log('处理后的图片URL:', item.imgUrl);
            }
            return item;
          });
          this.total = res.data.data.total
        } else {
          this.$message.error('获取作品失败')
        }
      } catch (error) {
        console.error('获取作品失败', error)
        this.$message.error('获取作品失败')
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchUserPhotos()
    },
    handlePhotoSuccess(res) {
      if (res && res.data && res.data.code === 1) {
        // 处理图片URL，使用完整URL
        let imageUrl = res.data.data;
        if (imageUrl && imageUrl.startsWith('/upload/')) {
          imageUrl = `${window.location.origin}/api${imageUrl}`;
          console.log('上传成功后的图片URL:', imageUrl);
        }
        this.photoForm.imgUrl = imageUrl;
        this.$message.success('图片上传成功');
      } else {
        const errorMsg = res && res.data && res.data.msg ? res.data.msg : '图片上传失败';
        this.$message.error(errorMsg);
      }
    },
    beforePhotoUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      
      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      
      return isImage && isLt5M
    },
    submitUpload() {
      if (!this.photoForm.imgUrl) {
        this.$message.warning('请上传作品图片')
        return
      }
      
      this.$refs.photoForm.validate(async valid => {
        if (valid) {
          this.uploading = true
          try {
            // 设置用户信息
            this.photoForm.userId = this.userId
            this.photoForm.author = this.nickname
            
            const res = await this.$http.post('/photos', this.photoForm)
            if (res.data.code === 1) {
              this.$message.success('作品上传成功，等待管理员审核')
              this.uploadDialogVisible = false
              this.resetPhotoForm()
              this.fetchUserPhotos()
            } else {
              this.$message.error(res.data.msg || '上传失败')
            }
          } catch (error) {
            console.error('上传作品失败', error)
            this.$message.error('上传失败，请稍后重试')
          } finally {
            this.uploading = false
          }
        }
      })
    },
    resetPhotoForm() {
      this.photoForm = {
        title: '',
        type: 1,
        description: '',
        imgUrl: '',
        userId: '',
        author: ''
      }
      if (this.$refs.photoForm) {
        this.$refs.photoForm.resetFields()
      }
    },
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        title: row.title,
        type: row.type,
        description: row.description
      }
      this.editDialogVisible = true
    },
    submitEdit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.editing = true
          try {
            const res = await this.$http.put('/photos', this.editForm)
            if (res.data.code === 1) {
              this.$message.success('修改成功')
              this.editDialogVisible = false
              this.fetchUserPhotos()
            } else {
              this.$message.error(res.data.msg || '修改失败')
            }
          } catch (error) {
            console.error('修改作品失败', error)
            this.$message.error('修改失败，请稍后重试')
          } finally {
            this.editing = false
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该作品吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await this.$http.delete(`/photos/${row.id}`)
          if (res.data.code === 1) {
            this.$message.success('删除成功')
            // 如果当前页只有一条数据，且不是第一页，则返回上一页
            if (this.photoList.length === 1 && this.currentPage > 1) {
              this.currentPage--
            }
            this.fetchUserPhotos()
          } else {
            this.$message.error(res.data.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除作品失败', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    getStatusTagType(status) {
      return status === 0 ? 'warning' : status === 1 ? 'success' : 'info';
    },
    getStatusText(status) {
      return status === 0 ? '待审核' : status === 1 ? '已上线' : '已下线';
    },
    viewPhotoDetail(id) {
      this.$router.push(`/photo/${id}`);
    },
    async customUpload(options) {
      try {
        const formData = new FormData();
        formData.append('file', options.file);
        
        const res = await this.$http.post('/photos/upload', formData);
        // Pass the entire response object to onSuccess
        options.onSuccess(res);
      } catch (error) {
        options.onError(error);
        console.error('上传失败:', error);
      }
    }
  }
}
</script>

<style scoped>
.user-photos {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #34495e;
  font-size: 24px;
}

.empty-block {
  margin: 40px 0;
  text-align: center;
}

.photo-grid {
  margin-top: 20px;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.photo-item {
  transition: all 0.3s;
}

.photo-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.photo-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.photo-preview {
  height: 180px;
  overflow: hidden;
  position: relative;
  cursor: pointer;
}

.el-image {
  width: 100%;
  height: 100%;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.photo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.photo-card:hover .photo-overlay {
  opacity: 1;
}

.view-text {
  color: white;
  font-size: 16px;
  padding: 8px 15px;
  border: 2px solid white;
  border-radius: 20px;
}

.photo-content {
  padding: 15px;
}

.photo-title {
  margin: 0 0 10px;
  font-size: 16px;
  color: #34495e;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.photo-meta {
  margin-bottom: 10px;
}

.photo-tag {
  margin-right: 5px;
}

.photo-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  color: #7f8c8d;
  font-size: 14px;
}

.stat-item i {
  margin-right: 5px;
}

.photo-actions {
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 30px;
  text-align: center;
}

.photo-uploader {
  text-align: center;
}

.photo {
  width: 200px;
  height: 200px;
  object-fit: cover;
}

.photo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

/* 列表动画 */
.photo-list-enter-active, .photo-list-leave-active {
  transition: all 0.5s;
}
.photo-list-enter, .photo-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: 1fr;
  }
  
  .photo-preview {
    height: 220px;
  }
}
</style> 